<template>
  <p style="line-height: 3.125rem; font-size: 1rem; font-weight: bold;" class="main_text">
    功能集合分配
  </p>
  <div class="main">
    <!-- #####################################底部##################################### -->
    <div class="p20">
      <!-- :row-class-name="tableRowClassName" -->
      <div class="mb20">
        <el-button type="primary" @click="AddRoleShow" v-if="roleList.write">添加功能集合</el-button>
        <!-- <el-button size="small">批量删除</el-button> -->
        <!-- <el-button type="danger" plain v-if="roleList.write">批量删除</el-button> -->
      </div>
      <!-- 表格 -->
      <el-table @selection-change="handleSelectionChange" :data="tableData" style="width: 100%;" max-height="500"
        :header-cell-style="{ background: '#f0f6fe' }" :show-overflow-tooltip="true" v-adaptive border>
        :header-cell-style="{ background: '#f0f6fe' }" :show-overflow-tooltip="true" v-adaptive border>
        <el-table-column type="selection" width="50" />
        <el-table-column label="ID" prop="id" />
        <el-table-column label="功能名称" prop="name" />
        <!-- <el-table-column label="所属单位" prop="nodeName" /> -->
        <!-- <el-table-column label="角色级别" prop="roleLevel" /> -->
        <el-table-column label="后台/小程序">
          <template #default="props">
            <el-tag v-if="props.row.code == '小程序'">小程序</el-tag>
            <el-tag v-else-if="props.row.code == '后台'" type="success">后台</el-tag>
            <el-tag v-else type="info">未选择</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="状态" prop="state" /> -->
        <el-table-column label="操作" fixed="right">
          <template #default="props" v-if="roleList.write">
            <el-button size="small" link type="primary" @click="editRole(props.row)">修改</el-button>
            <el-popconfirm title="确定要删除吗" @confirm="delRole(props.row.id)">
              <template #reference>
                <el-button size="small" link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
            <!-- <el-button v-if="props.row.code == '后台'" size="small" link type="primary"
                            @click="PermissionSetting(props.row)">后台权限设置</el-button>
                        <el-button v-if="props.row.code == '小程序'" size="small" link type="primary"
                            @click="AppletSetting(props.row)">小程序权限设置</el-button> -->
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" prop="remark" /> -->
      </el-table>
      <!-- 分页器 -->
      <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
        @change="handleCurrentChange" />
      <!-- #################################### 蒙层-----添加员工 #################################### -->
      <el-dialog v-model="centerDialogVisible" align-center width="40%" @close="closeCenterDialogVisible">
        <template #header>
          <div class="df aic">
            <el-icon style="color: #fff;" size="20">
              <Edit />
            </el-icon>&nbsp;
            <p style="color: #fff;">添加功能集合</p>
          </div>
        </template>
        <el-form :model="Addform" ref="AddformRef" :rules="AddformRules" class="df fww" label-position="left"
          v-if="closeCenterDialogVisibleShowFlag">
          <el-form-item label-width="7rem" label="功能名称：" style="width: 46%;" class="mr20" prop="name">
            <el-input v-model="Addform.name" placeholder="" />
          </el-form-item>
          <el-form-item label-width="8rem" label="后台/小程序：" style="width: 46%;" prop="code">
            <el-select v-model="Addform.code" placeholder="" @change="changeType">
              <el-option label="后台" value="后台" />
              <el-option label="小程序" value="小程序" />
            </el-select>
          </el-form-item>
        </el-form>
        <el-divider />
        <br />
        <p class="title">添加权限</p>
        <br />
        <!-- ##############树状############## -->
        <el-scrollbar max-height="22.5rem" v-if="addFunctionRole">
          <el-tree ref="treeRef" :data="dataSource" show-checkbox default-expand-all node-key="id">
            <template #default="{ node, data }" v-if="Addform.code != '小程序'">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <el-radio-group v-if="data.children == null" v-model="data.authorize" size="small">
                  <el-radio label="R">仅查看</el-radio>
                  <el-radio label="W">可编辑</el-radio>
                </el-radio-group>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="AddRole(AddformRef)">
              添加功能集合&权限
            </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- #################################### 蒙层-----修改员工权限 #################################### -->
      <el-dialog v-model="EditcenterDialogVisible" title="重新分配后台权限" align-center width="40%" @close="HtDiag">
        <!-- #########################################树状######################################### -->
        <template #header>
          <div class="df aic">
            <el-icon style="color: #fff;" size="20">
              <Edit />
            </el-icon>&nbsp;
            <p style="color: #fff;">重新分配后台权限</p>
          </div>
        </template>
        <el-scrollbar height="22.5rem">
          <el-tree ref="treeRefCheck" :data="dataSource" show-checkbox default-expand-all node-key="id"
            :default-checked-keys="HtcheckArr">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <el-radio-group v-if="data.children == null" v-model="data.authorize" size="small">
                  <el-radio label="R">仅查看</el-radio>
                  <el-radio label="W">可编辑</el-radio>
                </el-radio-group>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="EditcenterDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveData">保存</el-button>
            <!-- @click="saveRole" -->
          </span>
        </template>
      </el-dialog>
      <!-- #################################### 蒙层-----小程序权限设置 #################################### -->
      <el-dialog v-model="XiaoEditcenterDialogVisible" title="重新分配小程序权限" align-center width="40%" @close="XiaoDiag">
        <template #header>
          <div class="df aic">
            <el-icon style="color: #fff;" size="20">
              <Edit />
            </el-icon>&nbsp;
            <p style="color: #fff;">重新分配小程序权限</p>
          </div>
        </template>
        <!-- #########################################树状######################################### -->
        <el-scrollbar height="22.5rem">
          <el-tree ref="treeRefCheckXiao" :data="dataSource" show-checkbox default-expand-all node-key="id"
            :default-checked-keys="XiaoCheckArr">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <el-radio-group v-model="data.authorize" size="small">
                  <el-radio label="R">仅查看</el-radio>
                  <el-radio label="W">可编辑</el-radio>
                </el-radio-group>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="XiaoEditcenterDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveDataXiao">保存</el-button>
            <!-- @click="saveRole" -->
          </span>
        </template>
      </el-dialog>
      <!-- #################################### 蒙层-----修改员工信息 #################################### -->
      <el-dialog v-model="EditXcenterDialogVisible" align-center width="40%" @close="EditDiog">
        <template #header>
          <div class="df aic">
            <el-icon style="color: #fff;" size="20">
              <Edit />
            </el-icon>&nbsp;
            <p style="color: #fff;">功能集合名称修改</p>
          </div>
        </template>
        <el-form :model="Editform" label-width="7.5rem" label-position="left">
          <div class="df jcsb">
            <el-form-item label="功能名称：" style="width: 46%;">
              <el-input v-model="Editform.name" disabled />
            </el-form-item>
            <el-form-item label="后台/小程序：" style="width: 46%;">
              <el-select v-model="Editform.code" @change="changeEditType" disabled>
                <el-option label="后台" value="后台" />
                <el-option label="小程序" value="小程序" />
              </el-select>
            </el-form-item>
          </div>
          <el-divider />
          <p class="title">编辑权限</p>
          <br />
          <!-- ##############树状############## -->
          <el-scrollbar max-height="22.5rem" v-if="Editform.code == '后台'">
            <div v-if="displayTreeFlag">
              <!-- {{dataSource}} -->
              <!-- {{dataSource}} -->
              <el-tree ref="EditTreeRef" :data="dataSource" show-checkbox default-expand-all node-key="id"
                :default-checked-keys="treeCheckArr">
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <el-radio-group v-if="data.children == null" v-model="data.authorize" size="small">
                      <el-radio label="R">仅查看</el-radio>
                      <el-radio label="W">可编辑</el-radio>
                    </el-radio-group>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-scrollbar>
          <el-scrollbar max-height="22.5rem" v-if="Editform.code == '小程序'">
            <div v-if="displayTreeFlag">
              <el-tree ref="EditTreeRef" :data="dataSource" show-checkbox default-expand-all node-key="id"
                :default-checked-keys="XiaotreeCheckArr">
                <!-- <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                    <el-radio-group v-model="data.authorize" size="small">
                      <el-radio label="R">仅查看</el-radio>
                      <el-radio label="W">可编辑</el-radio>
                    </el-radio-group>
                  </span>
                </template> -->
              </el-tree>
            </div>
          </el-scrollbar>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="EditXcenterDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="EditSaveRole"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Edit } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  RequestSysRoleDel,
  RequestSysRoleSave,
  RequestSysRoleGetFunctionByRole,
  RequestSysFunctionGetUniFunction,
  RequestSysRoleGetlistlimit,
  RequestSysFunctionGetAllFunctionTree,
} from "../../../api/path/index.js";
import { ref } from "vue";
import useAuthorize from "@/hooks/authorize";
let roleList = useAuthorize()
/* 表格 */
const radio = ref("1");
const centerDialogVisible = ref(false);
const EditcenterDialogVisible = ref(false);
const EditXcenterDialogVisible = ref(false);
const XiaoEditcenterDialogVisible = ref(false);
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};
const tableData = ref<any>([]);
const dataSource = ref<any>([]);
const Addform = ref<any>({
  name: "",
  roleLevel: "",
  remarks: "",
  code: "",
});
/* 获取小程序权限 */
const xiaoGetData = () => {
  RequestSysFunctionGetUniFunction().then((res: any) => {
    dataSource.value = JSON.parse(
      JSON.stringify(res.resultObj).replace(/name/g, "label")
    );
    // console.log(dataSource.value);
    recursionSectionArr(dataSource.value);
  });
};
/* 获取后台权限 */
const houTaiGetData = () => {
  let treeData = ref<any>(
    localStorage.getItem("roleRoutes")?.replace(/name/g, "label")
  );
  dataSource.value = JSON.parse(treeData.value);
  // console.log(dataSource.value);
  recursionSectionArr(dataSource.value);
};
let recursionSectionArr = (arr: any) => {
  arr.forEach((item: any) => {
    // console.log("1231", item);
    // item.authorize = "W";
    // item.authorize = "W";
    if (item.children == null) {
      // item.authorize = "W";
      // item.authorize = "W";
      if (item.children != null) {
        recursionSectionArr(item.children);
      } else {
        return item;
      }
    } else {
      // item.authorize = "W";
      // item.authorize = "W";
      if (item.children != null) {
        recursionSectionArr(item.children);
      } else {
        return item;
      }
    }
  });
};
const changeType = (event: any) => {
  if (event == "后台") {
    houTaiGetData();
  } else if (event == "小程序") {
    xiaoGetData();
  }
};
const Editform = ref<any>();
/* ************************************************************** 获取角色信息列表 ***************************************************************/
const total = ref<any>(10);
const currentPage = ref(1);
const pageSize = ref(10);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getData();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getData();
};
const getData = () => {
  RequestSysRoleGetlistlimit({
    page: currentPage.value,
    rows: pageSize.value,
  }).then((res: any) => {
    tableData.value = res.resultObj.data;
    total.value = res.resultObj.total;
  });
  /* 渲染权限 */
};
getData();
/* ************************************************************** 删除单个角色 ***************************************************************/
const delRole = (id: any) => {
  RequestSysRoleDel(id).then((res: any) => {
    ElMessage.success(res.msg);
    getData();
  });
};
/* ************************************************************** 添加角色 ***************************************************************/
const checkId = ref<any>([]);
const treeRef = ref<any>();
const AddformRef = ref<any>()
const AddformRules = ref<any>({
  name: [
    { required: true, message: "请输入功能名称", trigger: "change" },
  ],
  code: [
    { required: true, message: "请选择功能类型", trigger: "change" },
  ]
});
const closeCenterDialogVisibleShowFlag = ref<any>(true)
const AddRoleShow = () => {
  centerDialogVisible.value = true
  closeCenterDialogVisibleShowFlag.value = true
  addFunctionRole.value = true
}
const closeCenterDialogVisible = () => {
  dataSource.value = []
  Addform.value.name = ''
  Addform.value.code = ''
  closeCenterDialogVisibleShowFlag.value = false
}
const addFunctionRole = ref<any>(true)
const AddRole = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate((valid: any) => {
    if (valid) {
      /* 获取权限树选中的节点ID */
      console.log("Addform.value", Addform.value);
      treeRef.value!.getCheckedNodes(false, true).forEach((item: any) => {
        // console.log('item', item);
        checkId.value.push({
          sysFunctionId: item.id,
          dispatchMode: "N",
          authorize: item.authorize,
        });
      });
      checkId.value.push({
        sysFunctionId: 0,
        dispatchMode: "N",
        authorize: "",
      });
      //后台/小程序：
      if (Addform.value.code == '小程序') {
        checkId.value.push({
          sysFunctionId: 137,
          dispatchMode: "N",
          authorize: "",
        });
      }
      console.log("asdasda", checkId.value);
      let node = JSON.parse(localStorage.getItem("roleInfo")!).company;
      const blob = new Blob(
        [
          JSON.stringify({
            node: node,
            state: "1",
            name: Addform.value.name,
            remarks: Addform.value.remarks,
            roleLevel: Addform.value.roleLevel,
            code: Addform.value.code,
            nodeScope: "n",
          }),
        ],
        {
          type: "application/json;charset=utf-8",
        }
      );
      console.log('checkId.value', checkId.value);
      const blob2 = new Blob([JSON.stringify(checkId.value)], {
        type: "application/json;charset=utf-8",
      });
      let AddRoleForm = new FormData();
      AddRoleForm.append("sys_role", blob);
      AddRoleForm.append("sys_functions", blob2);
      RequestSysRoleSave(AddRoleForm).then((res: any) => {
        console.log(res);
        ElMessage.success(res.msg);
        addFunctionRole.value = false
        centerDialogVisible.value = false;
        checkId.value = [];
        getData();
      });
    }
  });
};

/* ************************************************************** 修改角色 ***************************************************************/
const editID = ref<any>(); //修改需要携带的id
const changeEditType = (event: any) => {
  if (event == "后台") {
    houTaiGetData();
  } else if (event == "小程序") {
    xiaoGetData();
  }
};
let recursionSectionArrVal = (arr: any, checkedKeys: any) => {
  arr.forEach((item: any) => {
    if (item.children != null) {
      recursionSectionArrVal(item.children, checkedKeys);
    } else {
      checkedKeys.push(item.id);
      return item;
    }
  });
};
const treeCheckArr = ref<any>([]);
const XiaotreeCheckArr = ref<any>([]);
const displayTreeFlag = ref<any>(false);
const huixianArrFunction = ref<any>([])
// 按钮权限回显
const huixianArr = (arr: any) => {
  arr.forEach((item: any) => {
    if (item.children == null) {
      huixianArrFunction.value.push(item);
      if (item.children != null) {
        huixianArr(item.children);
      } else {
        return item;
      }
    } else {
      // item.authorize = "W";
      if (item.children != null) {
        huixianArr(item.children);
      } else {
        return item;
      }
    }
  });
};
const huixianArr1 = (arr: any) => {
  arr.forEach((item: any) => {
    if (item.children == null) {
      huixianArrFunction.value.forEach((element: any) => {
        if (item.label == element.name) {
          item.name = item.label
          item.authorize = element.authorize
        }
      });
      if (item.children != null) {
        huixianArr1(item.children);
      } else {
        return item;
      }
    } else {
      // item.authorize = "W";
      if (item.children != null) {
        huixianArr1(item.children);
      } else {
        return item;
      }
    }
  });
};
const editRole = async (row: any) => {
  dataSource.value = [];
  Editform.value = row;
  if (row.code == "后台") {
    houTaiGetData();
    let res = await RequestSysRoleGetFunctionByRole(row.id);
    recursionSectionArrVal(res.resultObj.pc[0].children, treeCheckArr.value);
    EditXcenterDialogVisible.value = true;
    displayTreeFlag.value = true;
    console.log('res.resultObj.pc[0].children', res.resultObj.pc[0].children);
    dataSource.value.forEach((item: any) => {
      res.resultObj.pc[0].children.forEach((val: any) => {
        if (item.label == val.name) {
          item.children = val.children
        }
      });
    })
    dataSource.value = JSON.parse(JSON.stringify(dataSource.value).replace(/name/g, "label"));
    console.log("dataSource.value", dataSource.value);
  } else if (row.code == "小程序") {
    xiaoGetData();
    let res = await RequestSysRoleGetFunctionByRole(row.id);
    recursionSectionArrVal(res.resultObj.uni, XiaotreeCheckArr.value);
    EditXcenterDialogVisible.value = true;
    displayTreeFlag.value = true;
    console.log("XiaotreeCheckArr.value", XiaotreeCheckArr.value);
  } else {
    EditXcenterDialogVisible.value = true;
  }
  editID.value = row.id;
};
const EditDiog = () => {
  getData();
  treeCheckArr.value = [];
  XiaotreeCheckArr.value = [];
  displayTreeFlag.value = false;
};
const EditTreeRef = ref<any>();
const EditIdDataXiao = ref<any>([]);
const EditSaveRole = () => {
  EditTreeRef.value!.getCheckedNodes(false, true).forEach((item: any) => {
    // console.log('item', item);
    EditIdDataXiao.value.push({
      sysFunctionId: item.id,
      dispatchMode: "N",
      authorize: item.authorize,
    });
    EditIdDataXiao.value.push({
      sysFunctionId: 0,
      dispatchMode: "N",
      authorize: item.authorize,
    });
    EditIdDataXiao.value.push({
      sysFunctionId: 137,
      dispatchMode: "N",
      authorize: "",
    });
  });
  console.log("EditIdDataXiao.value", EditIdDataXiao.value);
  const blob = new Blob(
    [
      JSON.stringify({
        id: editID.value,
        node: Editform.value.company_node,
        state: "1",
        code: Editform.value.code,
        name: Editform.value.name,
        nodeScope: "n",
      }),
    ],
    {
      type: "application/json;charset=utf-8",
    }
  );
  const blob2 = new Blob([JSON.stringify(EditIdDataXiao.value)], {
    type: "application/json;charset=utf-8",
  });
  let EditRoleForm = new FormData();
  EditRoleForm.append("sys_role", blob);
  EditRoleForm.append("sys_functions", blob2);
  RequestSysRoleSave(EditRoleForm).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      EditXcenterDialogVisible.value = false;
      EditIdDataXiao.value = []
      getData();
    }
  });
};
/* ************************************************************** 修改权限设置 ***************************************************************/
/* 节点树选中所需要的ID数组 */
const HtcheckArr = ref<any>([]);
const saveID = ref<any>("");
/* ************************************************************** 保存权限 ***************************************************************/
const saveIdData = ref<any>([]);
const treeRefCheck = ref<any>();
const saveData = () => {
  /* 获取权限树选中的节点ID */
  // checkId.value = treeRef.value!.getCheckedNodes(false, false)
  console.log(treeRefCheck.value!.getCheckedNodes(false, true));
  treeRefCheck.value!.getCheckedNodes(false, true).forEach((item: any) => {
    // console.log('item', item);
    saveIdData.value.push({
      sysFunctionId: item.id,
      dispatchMode: "N",
      authorize: item.authorize,
    });
  });
  saveIdData.value.push({
    sysFunctionId: 0,
    dispatchMode: "N",
    authorize: "",
  });
  console.log("saveIdData.value", saveIdData.value);
  const blob = new Blob(
    [
      JSON.stringify({
        node: saveID.value.node,
        state: saveID.value.state,
        name: saveID.value.name,
        // roleLevel: saveID.value.roleLevel,
        nodeScope: saveID.value.node_scope,
        id: saveID.value.id,
      }),
    ],
    {
      type: "application/json;charset=utf-8",
    }
  );
  const blob2 = new Blob([JSON.stringify(saveIdData.value)], {
    type: "application/json;charset=utf-8",
  });
  const AddRoleForm = new FormData();
  AddRoleForm.append("sys_role", blob);
  AddRoleForm.append("sys_functions", blob2);
  RequestSysRoleSave(AddRoleForm).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      EditcenterDialogVisible.value = false;
      getData();
    }
  });
};
/* ************************************************************** 小程序权限设置 ***************************************************************/
const saveIDXiao = ref<any>("");
const XiaoCheckArr = ref<any>([]);
/* 保存 */
const treeRefCheckXiao = ref<any>();
const saveIdDataXiao = ref<any>([]);
const saveDataXiao = () => {
  // treeRefCheckXiao.value!.getCheckedKeys(false, false).forEach((item: any) => {
  //     saveIdDataXiao.value.push({
  //         sysFunctionId: item,
  //         dispatchMode: 'N',
  //     })
  // })
  treeRefCheckXiao.value!.getCheckedNodes(false, false).forEach((item: any) => {
    // console.log('item', item);
    saveIdDataXiao.value.push({
      sysFunctionId: item.id,
      dispatchMode: "N",
      authorize: item.authorize,
    });
  });
  console.log("saveIdDataXiao.value", saveIdDataXiao.value);
  const blob = new Blob(
    [
      JSON.stringify({
        node: saveIDXiao.value.node,
        state: saveIDXiao.value.state,
        name: saveIDXiao.value.name,
        nodeScope: saveIDXiao.value.node_scope,
        id: saveIDXiao.value.id,
      }),
    ],
    {
      type: "application/json;charset=utf-8",
    }
  );
  const blob2 = new Blob([JSON.stringify(saveIdDataXiao.value)], {
    type: "application/json;charset=utf-8",
  });
  let AddRoleForm = new FormData();
  AddRoleForm.append("sys_role", blob);
  AddRoleForm.append("sys_functions", blob2);
  RequestSysRoleSave(AddRoleForm).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      XiaoEditcenterDialogVisible.value = false;
      getData();
    }
  });
};
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  background-color: #fff;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 0.875rem;
  padding-right: 0.5rem;
}

.title {
  line-height: var(--el-dialog-font-line-height);
  font-size: 1.125rem;
  color: var(--el-text-color-primary);
}

/* 弹出框样式 */
::v-deep .el-overlay {
  .el-dialog__header {
    background-color: #116cf8;
    margin-right: 0;

    .el-icon svg {
      color: #fff;
    }
  }

  .el-dialog__title {
    color: #fff;
  }
}

::v-deep .el-select {
  width: 100%;
}
</style>
